<?php

namespace Luka\WindowBundle\Controller\Helpers;

use Luka\NavigationBundle\Model\Item;

class MenuHelper {
    function __construct(){
        define('MENU_DEPTH', 2);
    }

    public function SetPages($em, $locale, $depth, $params, $route, $parentId = null){
        $output = array();
        if($depth < MENU_DEPTH){
            $input = $this->GetPages($em, $locale, $parentId);
            $depth++;
            foreach ($input as $value) {
                $pageId = $value["id"];
                $subPages = $this->SetPages($em, $locale, $depth, $params, $route, $pageId);
                $route_path = '_'.$value["controller"].'_'.$value["action"];
                $url = $route->generate($route_path, array('id' => $pageId));
                $output[] = new Item(
                    $value["linktitle"],
                    $url,
                    array(),
                    $subPages,
                    $this->IsSelected($pageId, $route_path, $params),
                    $this->isChildSelected($subPages)
                );
            }
        }
        return $output;
    }

    private function GetPages($em, $locale, $parentId = null){
        $query = $em->createQuery('
            SELECT p.id, p.linktitle, p.action, type.name as controller FROM LukaStoreBundle:Page p
            JOIN p.pagetype type
            LEFT JOIN p.parent parent
            WHERE p.visibility = :visibility
            AND p.language = :language
            AND parent '.(isset($parentId) ? ("= ".$parentId) : "is null").'
            ORDER BY p.ordernumber
        ')
            ->setParameters(
            array(
                "visibility" => "1",
                "language" => $locale
            )
        );

        return $query->getArrayResult();
    }

    private function IsSelected($pageId, $route_path, $params){
        $idValid = (isset($params["id"]) ? ($pageId == $params["id"]) : true);
        return ($idValid && $route_path == $params["_route"]);
    }

    public function isChildSelected($array) {
        foreach($array as $item){
            if($item->selected){
                return true;
            }
        }
        return false;
    }
}
